<template>
  <div class="xtx-pagination">
    <span v-if="myCurrentPage <= 1" class="btn disabled">上一页</span>
    <span v-else @click="handlerPage(myCurrentPage-1)" class="btn">上一页</span>
    <span class="dot" v-if="page.start > 1">...</span>
    <span @click="handlerPage(i)" v-for="i in page.btnArr" :key="i" class="btn" :class="{active:myCurrentPage===i}">{{i}}</span>
    <span class="dot" v-if="page.end < page.totalPage">...</span>
    <span v-if="myCurrentPage >= page.totalPage" class="btn disabled">下一页</span>
    <span v-else @click="handlerPage(myCurrentPage+1)" class="btn">下一页</span>
  </div>
</template>

<script>
export default {
  name: 'xtx-pagination',
  props: {
    total: {
      type: Number,
      default: 0
    },
    pageSize: {
      type: Number,
      default: 10
    },
    currentPage: {
      type: Number,
      default: 1
    }
  },
  watch: {
    currentPage: {
      immediate: true,
      handler () {
        this.myCurrentPage = this.currentPage
      }
    }
  },
  data () {
    return {
      myCurrentPage: 1
    }
  },
  computed: {
    page () {
      const totalPage = Math.ceil(this.total / this.pageSize)
      const currentPage = this.myCurrentPage
      const buttonCount = 5
      let start = null
      let end = null
      // 第一轮，理想情况，根据当前页取出起始和结束页码
      start = currentPage - Math.floor(buttonCount / 2)
      end = start + buttonCount - 1
      // 第二轮，如果起始页码小于1，重新计算起始和结束页码
      if (start < 1) {
        start = 1
        end = (start + buttonCount - 1) > totalPage ? totalPage : start + buttonCount - 1
      }
      // 第三轮，如果结束页码大于总页数，重新计算起始和结束页码
      if (end > totalPage) {
        end = totalPage
        start = (end - buttonCount + 1) < 1 ? 1 : (end - buttonCount + 1)
      }
      const btnArr = []
      for (let i = start; i <= end; i++) {
        btnArr.push(i)
      }
      return { totalPage, start, end, btnArr }
    }
  },
  methods: {
    handlerPage (newPage) {
      if (newPage !== this.myCurrentPage) {
        this.myCurrentPage = newPage
        this.$emit('update:current-page', newPage)
        this.$emit('current-change', newPage)
      }
    }
  }
}
</script>

<style scoped lang='less'>
.xtx-pagination {
  display: flex;
  justify-content: center;
  padding: 20px 0;
  user-select: none;
  .dot {
    margin-right: 10px;
    color: #999;
  }
  .btn {
    height: 30px;
    line-height: 28px;
    padding: 0 10px;
    border: 1px solid #e4e4e4;
    border-radius: 4px;
    margin-right: 10px;
    color: #666;
    cursor: pointer;
    &:hover {
      color: @xtxColor;
    }
    &.active {
      border-color: @xtxColor;
      color: #fff;
      background-color: @xtxColor;
    }
    &.disabled {
      border-color: #f5f5f5;
      color: #ccc;
      cursor: not-allowed;
    }
  }
}
</style>
